import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'dart:isolate';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:my_app/007--%E7%BD%91%E7%BB%9C&%E5%A4%9A%E7%BA%BF%E7%A8%8B/007_asynetwork.dart';

class dioDemo008 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.grey,
        highlightColor: Color.fromRGBO(1, 0, 0, 0.0),//透明
        splashColor: Color.fromRGBO(1, 0, 0, 0.0),//水波纹
      ),
      home: dioDemo008Page(),
    );
  }
}
class dioDemo008Page extends StatefulWidget {
  @override
  _dioDemo008tate createState() => _dioDemo008tate();
}

class _dioDemo008tate extends State<dioDemo008Page> {
  @override
  Widget build(BuildContext context) {
    return Text('_dioDemo008_dio');
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // isolateDemo();////如果你返回的是compute的Future，那个这个这个任务就在子Isolate的事件队列中
    // TimerDemo();//Future也是基于timer

    dioDemo();

  }
}

void TimerDemo() {
  int _count = 0;

//  Timer.periodic(Duration(milliseconds: 1000), (timer) {
//    _count++;
//    print(_count);
//    if (_count == 1000) {
//      timer.cancel();
//    }
//  });
}

void isolateDemo() {
  Future(() {
    compute(func1, 123);
  }).then((value) => print('1结束'));
  Future(() {
    compute(func1, 123);
  }).then((value) => print('2结束'));
  Future(() {
    compute(func1, 123);
  }).then((value) => print('3结束'));
  Future(() {
    compute(func1, 123);
  }).then((value) => print('4结束'));
  Future(() {
    compute(func1, 123);
  }).then((value) => print('5结束'));

//  downloadDemo1().then((value) => print('1结束'));
//  downloadDemo1().then((value) => print('2结束'));
//  downloadDemo1().then((value) => print('3结束'));
//  downloadDemo1().then((value) => print('4结束'));
//  downloadDemo1().then((value) => print('5结束'));
//  downloadDemo1().then((value) => print('6结束'));
}

Future downloadDemo1() async {
  return Future(() {
    //在主线程，闲时执行
    // print('loadData1：'+Isolate.current.debugName);

    //有序的,Future有序添加，Future有序执行，Future有序结束
    compute(func1,1);

    //如果你返回的是compute的Future，那个这个这个任务就在子Isolate的事件队列中
    // return compute(func1,1);// 无序的
  });
}

int func1(int msg) {
  return 10;
}

void dioDemo() async {
  //发送网络请求
  //1.创建dio对象
  final dio = Dio();
  dio.get('path');
  //2.下载数据
  var downloadUrl =
      'http://pub.idqqimg.com/pc/misc/groupgift/fudao/CourseTeacher_1.3.16.80_DailyBuild.dmg';
  var downloadUrl2 =
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591639688346&di=e515c345de00b89b54f1a35ae240b630&imgtype=0&src=http%3A%2F%2Fpic3.16pic.com%2F00%2F01%2F11%2F16pic_111395_b.jpg';

  String savePath = '/Users/jun/123/腾讯课题.dmg';
  //获取temp路径!
  String savePath2 = Directory.systemTemp.path + '/腾讯课堂.dmg';
  print(savePath2);
  // Response m = await download3(dio, downloadUrl, savePath);
  Response n = await download3(dio, downloadUrl2, savePath);
  download2(dio, downloadUrl, savePath);
}

Future download3(Dio dio, String url, String savePath) async {
  return dio.download(url, (header) {
    return savePath;
  }).then((value) => print(url));
}

void download2(Dio dio, String url, String savePath) {
  dio
      .download(url, (header) {
        return savePath;
      }, onReceiveProgress: showDownloadProgress)
      .whenComplete(() => print('完成'))
      .catchError((e) => print(e));
}

void download1(Dio dio, String url, savePath) {
  dio
      .download(url, savePath, onReceiveProgress: showDownloadProgress)
      .then((value) => print(value))
      .whenComplete(() => print('结束了'))
      .catchError((e) => print(e));
}

void showDownloadProgress(received, total) {
  if (total != -1) {
    print((received / total * 100).toStringAsFixed(0) + "%");
  }
}

//Another way to downloading small file

void computeTest() async {
  print('外部代码1');

  int a = await compute(func2, 10);
  print('a=$a');
  sleep(Duration(seconds: 2));
  print('外部代码2');
}

int func2(int mun) {
  return 10000;
}

void isolateTest() async {
  print('外部代码1');
  //创建一个port
  ReceivePort portMain = ReceivePort();
  var portThread;

  //创建isolate
  Isolate iso = await Isolate.spawn(func, portMain.sendPort);
  portMain.listen((message) {
    print(Isolate.current.debugName);
    portThread = message;
  });

  print('外部代码2');
}

int a = 10;

void func(SendPort portMain) {
  print(Isolate.current.debugName);
  sleep(Duration(seconds: 1));
  portMain.send(1000);
}

void testFuture4() {
  Future x1 = Future(() => scheduleMicrotask(() => print('1')));

  scheduleMicrotask(() => print('2')); //1

  Future x = Future(() => print('6'));

  x1.then((value) {
    print('3');
    scheduleMicrotask(() => print('4'));
  }).then((value) => print('5'));

//  Future x = Future(() => print('1'));
//  x.then((value) {
//    print('4');
//    Future(() => print('9'));
//  }).then((value) => print('10'));
//
//  Future(() => print('2'));
}

void testFuture3() {
  print('外部代码1');
  Future(() => print('A')).then((value) => print('A结束'));
  Future(() => print('B')).then((value) => print('B结束'));
  scheduleMicrotask(() {
    print('微任务A');
  });
  sleep(Duration(seconds: 2));
  print('外部代码2');
}

void testFuture2() async {
  Future.wait([
    Future(() {
      return '任务1';
    }),
    Future(() {
      return '任务2';
    }),
  ]).then((value) {
    print(value[0] + value[1]);
  });
}

void testFuture() async {
  Future(() {
    sleep(Duration(seconds: 2));
    return '任务1';
  }).then((value) {
    print('$value结束');
    return '$value任务2';
  }).then((value) {
    print('$value结束');
    return '$value任务3';
  }).then((value) {
    print('$value结束');
    return '$value任务4';
  });
  print('任务添加完毕');
}
//
//  Future(() {
//    sleep(Duration(seconds: 2));
//    return '任务2';
//  }).then((value) {
//    print('$value结束');
//  });

String _data = '0';
getData() async {
  print('开始data=$_data');

  thenFunc(value) {
    print('then 进来了!');
    print('结束data=$value');
  }

  errorFunc(e) {
    print('error来了');
    print('捕获到了:' + e.toString());
  }

  Future future = Future(() {
    //耗时操作
    //1.后面的操作必须是异步才能用await修饰
    //2.当前行数也必须是异步函数
//    for (int i = 0; i < 1000000000; i++) {}
    sleep(Duration(seconds: 2)); //确定时间!
  })
      .then((value) {
        print('then 进来了!');
        print('结束data=$value');
      })
      .catchError(errorFunc)
      .whenComplete(() {
        print('完成了!');
      });

  print('再多干点事情');
}
